<template>
  <div style="display: flex; flex-direction: column; flex: 1; height: 100%">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="openAddType"> 添加分类 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="disabledBatchBtn">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="onUpdateStatus(false)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="onUpdateStatus(true)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="onBatchDel">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 列表关键词搜索 -->
      <div class="search">
        <el-input clearable v-model="search" @clear="getList" placeholder="关键词搜索" @keyup.enter="getList" />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <!-- 列表表格 -->
    <div class="table">
      <el-table
        v-loading="tableLoading"
        element-loading-text="加载中..."
        border
        stripe
        resizable
        :data="tableData"
        ref="tableMultipleRef"
        @selection-change="tableSelectionChange"
        style="position: absolute"
        height="100%"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column show-overflow-tooltip prop="name" label="分类名称" min-width="50" />
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="80">
          <template #default="scope">
            <HStatus v-if="scope.row.status === false">启用</HStatus>
            <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="updateTime" label="更新时间" width="160" />
        <el-table-column fixed="right" label="操作" width="50">
          <template #default="scope">
            <HLink @click="openEditType(scope.row)">编辑</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="footer">
      <Pagination
        ref="paginationRef"
        :list_total="totalData"
        @size-change="getList"
        @current-change="getList"
      />
    </div>
  </div>

  <!-- 新增/编辑分类弹窗 -->
  <div>
    <HModal v-model="addDialog" size="small">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ dialogTitle }}</h3>
        </div>
      </template>
      <div v-loading="dialogLoading" element-loading-text="加载中...">
        <div class="form-text">
          <el-form
            label-width="80"
            ref="typeFormRef"
            :rules="typeFormRule"
            :model="typeFormData"
            class="form_content"
            @validate="handleFormValidate"
          >
            <el-form-item
              label="类型名称"
              :class="{ form_item: formValidateResult, validate_fail: !formValidateResult }"
              prop="name"
            >
              <el-input v-model="typeFormData.name" clearable placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="类型状态" class="radio_form_item" prop="status">
              <el-radio-group v-model="typeFormData.status" class="el-group">
                <div class="radio_container">
                  <el-radio :value="false">
                    <span class="bg_text">启用</span>
                  </el-radio>
                  <el-radio :value="true">
                    <span class="bg_text">禁用</span>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footerLeft>
        <HPlainBgButton
          v-show="typeFormData.id"
          type="error"
          is-modal
          @click="delKnowledgeTypeData(typeFormData)"
          >删除</HPlainBgButton
        >
      </template>

      <template #footerRight>
        <HButton @click="saveType(typeFormRef)" is-modal type="primary">保存</HButton>
        <HButton @click="onClose" is-modal>取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts" name="knowType">
  import { ref, onMounted, markRaw, watch } from 'vue'
  import type { FormInstance, FormItemProp } from 'element-plus'
  import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
  import { Delete, Warning, Search, CircleCheck, ArrowDown } from '@element-plus/icons-vue'

  // 引入组件或工具
  import Pagination from '@/components/Pagination/index.vue' // 分页组件
  import {
    knowledgeTypeSave,
    getKnowledgeTypeList,
    getKnowledgeTypeDetail,
    deleteKnowledgeType,
    updateKnowledgeTypeDisable,
  } from '@/api/knowledge'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import { HModal } from '@/components/common'

  /**
   * 表单验证结果
   */
  const formValidateResult = ref(true)

  /**
   * 表单验证事件
   */
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    if (prop === 'name') {
      formValidateResult.value = isValid
    }
  }

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addDialog.value = false
    formValidateResult.value = true
  }

  const tableLoading = ref(false) // 列表请求加载
  const dialogLoading = ref(false) // 弹窗加载动画
  const addDialog = ref(false) // 新增/编辑分类弹窗
  const disabledBatchBtn = ref(true) // 是否禁用批量按钮事件
  const dialogTitle = ref('') // 弹窗标题
  const typeFormRef = ref<FormInstance>()
  const search = ref('') // 关键词搜索
  const typeFormData = ref({
    id: '', // 类型ID
    name: '', // 类型名称
    status: false, // 状态：false-启用，true-禁用
  })
  const paginationRef = ref() // 分页Ref对象
  const tableMultipleRef = ref<InstanceType<typeof ElTable>>() // 列表Ref实例对象
  const totalData = ref(0) // 总数目
  const tableData = ref([]) // 列表表格对象
  const tableSelectData = ref([]) // 列表选中的对象
  const delKnowledgeTypeIds = ref([]) // 删除知识库类型的ID数组对象
  // 校验规则
  const typeFormRule = ref({
    name: [{ required: true, message: '类型名称不能为空', trigger: ['blur', 'change'] }],
    status: [{ required: true, message: '类型状态不能为空', trigger: ['blur', 'change'] }],
  })

  // 打开新增弹窗
  const openAddType = () => {
    addDialog.value = true
    dialogTitle.value = '新增知识库类型'
    typeFormData.value = {
      id: '', // 分类ID
      name: '', // 分类名称
      status: false, // 状态：false-启用，true-禁用
    }
  }

  // 打开编码弹窗
  const openEditType = async (obj: any) => {
    addDialog.value = true
    dialogTitle.value = '编辑知识库类型'
    typeFormData.value = {
      id: '', // 类型ID
      name: '', // 类型名称
      status: false, // 状态：false-启用，true-禁用
    }
    dialogLoading.value = true
    await getKnowledgeTypeDetail(obj.id).then((resp) => {
      dialogLoading.value = false
      if (resp.data.code == 20000) {
        typeFormData.value = resp.data.data.row
      }
    })
  }

  // 校验并保存类型
  const saveType = (formEl: FormInstance) => {
    formEl.validate((valid) => {
      if (valid) {
        save()
      }
    })
  }

  // 列表选中框事件
  const tableSelectionChange = (val: any) => {
    tableSelectData.value = []
    tableSelectData.value = val
  }

  // 清空列表选中项
  const clearTableSelection = () => {
    tableMultipleRef.value!.clearSelection()
  }

  // 批量禁用或启用
  const onUpdateStatus = (status: boolean) => {
    const ids = []
    tableSelectData.value.forEach((item) => {
      ids.push(item.id)
    })
    ElMessageBox({
      title: '温馨提示',
      message: status
        ? `确认禁用 ${ids.length} 项？，禁用后将不可被其他应用使用！`
        : `确认启用 ${ids.length} 项？，启用后可被其他应用使用！`,
      type: 'warning',
      icon: markRaw(Warning),
      showCancelButton: true,
      confirmButtonText: status ? '确认禁用' : '确认启用',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = status ? '禁用中...' : '启用中...'
          setTimeout(() => {
            batchUpdateStatusApi(status, ids)
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 300)
          }, 1000)
        } else {
          done()
        }
      },
    })
  }

  // 批量删除
  const onBatchDel = () => {
    delKnowledgeTypeIds.value = []
    tableSelectData.value.forEach((item) => {
      delKnowledgeTypeIds.value.push(item.id)
    })
    ElMessageBox({
      title: '温馨提示',
      message: `确认删除选中的 ${tableSelectData.value.length} 项？，删除后将不可恢复！`,
      type: 'warning',
      icon: markRaw(Delete),
      showCancelButton: true,
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '删除中...'
          setTimeout(() => {
            delDataApi()
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 300)
          }, 1000)
        } else {
          done()
        }
      },
    })
  }

  // 删除知识库类型
  const delKnowledgeTypeData = (obj: any) => {
    delKnowledgeTypeIds.value = []
    delKnowledgeTypeIds.value.push(obj.id)
    ElMessageBox({
      title: '温馨提示',
      message: `确认删除[ ${obj.name} ]？，删除后将不可恢复！`,
      type: 'warning',
      icon: markRaw(Delete),
      showCancelButton: true,
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '删除中...'
          setTimeout(() => {
            delDataApi()
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 300)
          }, 1000)
        } else {
          done()
        }
      },
    })
  }

  // 启用或禁用知识库类型Api
  const batchUpdateStatusApi = (status: boolean, ids: any) => {
    updateKnowledgeTypeDisable(status, ids).then((resp) => {
      ElMessage({
        message: resp.data.message,
        type: resp.data.code !== 20000 ? 'error' : 'success',
        duration: 2000,
      })
      if (resp.data.code === 20000) {
        clearTableSelection()
        getList()
      }
    })
  }

  // 删除知识库类型的Api
  const delDataApi = async () => {
    await deleteKnowledgeType(delKnowledgeTypeIds.value).then((resp) => {
      ElMessage({
        message: resp.data.message,
        type: resp.data.code !== 20000 ? 'error' : 'success',
        duration: 2000,
      })
      if (resp.data.code === 20000) {
        delKnowledgeTypeIds.value = []
        clearTableSelection()
        addDialog.value = false
        getList()
      }
    })
  }

  // 保存知识库类型Api
  const save = async () => {
    dialogLoading.value = true
    await knowledgeTypeSave(typeFormData.value).then((resp) => {
      dialogLoading.value = false
      ElMessage({
        message: resp.data.message,
        type: resp.data.code !== 20000 ? 'error' : 'success',
        duration: 2000,
      })
      if (resp.data.code === 20000) {
        onClose()
        getList()
      }
    })
  }

  // 列表请求Api
  const getList = async () => {
    const searchData = {
      limit: paginationRef.value.size,
      page: paginationRef.value.current,
      name: search.value,
    }
    tableLoading.value = true
    await getKnowledgeTypeList(searchData).then((resp) => {
      tableLoading.value = false
      if (resp.data.code === 20000) {
        const data = resp.data.data
        tableData.value = data.rows
        totalData.value = Number(data.total)
      }
    })
  }

  // 监听列表是否选中
  watch(
    () => tableSelectData.value,
    () => {
      disabledBatchBtn.value = true
      if (tableSelectData.value.length > 0) {
        disabledBatchBtn.value = false
      }
    },
  )

  onMounted(() => {
    getList()
  })

  // 允许被调用的方法
  defineExpose({ getList })
</script>

<style lang="scss" scoped>
  @import './KnowType.scss';
</style>
